//
//  NiubiSearchVC.m
//  danpin
//
//  Created by chuangjia on 22/10/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "NiubiSearchVC.h"
#import "viewconfig.h"
#import "MDSearchBarController.h"
#import "ZShare.h"
#import "SVHTTPRequest.h"
#import "NSString+Extensions.h"
#import "BuyFromCell.h"
#import "BaiduCell.h"
#import "BaikeCell.h"
#import "NiubiTagCell.h"
#import "WebViewController.h"
#import "UIImage+GIF.h"
#import "DanpinCell.h"
#import "MgpyhCell.h"
#import "UMengShare.h"
#import "BaiChuanShare.h"//淘宝的商品，直接用百川显示
#import "SearchShare.h"
//百度语音
#import "BDVoiceRecognitionClient.h"
#import "BDVRSConfig.h"
#import "VoiceRecognition.h"

#import "HotwordsHistoryTableView.h"

#import "SearchProgressTableView.h"

#define TABLE_TOP_INSET 50


@interface NiubiSearchVC ()<MDSearchBarViewControllerDelegate,UITableViewDataSource,UITableViewDelegate>
{
    
}
//
@property (nonatomic,assign) float lastOffsetY;    //A variable define in headfile
@property (nonatomic,strong) UIButton * recordButton;

@property (nonatomic, strong) MDSearchBar * searchBar;
@property (nonatomic, strong) MDSearchBarController * searchBarController;
@property(nonatomic,strong)   NSMutableArray *suggArray;
@property(nonatomic,strong)   NSMutableArray *resultArray;
@property (nonatomic,strong)  NSMutableDictionary* dcTaobaoSku;

@property(nonatomic,strong)   UITableView *tbView;

@property(nonatomic,strong) HotwordsHistoryTableView * historyTableView;
@property(nonatomic,strong) SearchProgressTableView *  tableProgressBar;
;

@property (nonatomic, strong) NSDictionary * recommendURL;
@property (nonatomic, strong) NSArray * baseData;

@property (nonatomic,strong) NSString* strNameExpanded;
//@property (nonatomic,assign) long nShowMoreData;

@property(nonatomic,strong)   UIView *footerView;
@property(nonatomic,strong)   UIImageView *footerGifView;
@property(nonatomic,strong)   UILabel *footerIntroLabel;

//
@property(nonatomic,strong)UIView *progressBar;
@property(nonatomic,assign)CGFloat progress;
@property(nonatomic,assign)CGFloat process;
@property(nonatomic,assign)CGFloat totoalProgress;
//
@property (nonatomic,strong) NSString* strSearchTermEnglish;




@end

@implementation NiubiSearchVC
@synthesize recommendURL=_recommendURL;
@synthesize baseData=_baseData;
@synthesize suggArray=_suggArray;
@synthesize resultArray=_resultArray;
@synthesize tbView=_tbView;
@synthesize footerView=_footerView;
@synthesize footerGifView=_footerGifView;
@synthesize footerIntroLabel=_footerIntroLabel;

@synthesize progressBar=_progressBar;
@synthesize progress=_progress;
@synthesize process=_process;
@synthesize totoalProgress=_totoalProgress;
@synthesize strSearchTermEnglish=_strSearchTermEnglish;


//============================================
//百度语音识别
//============================================
-(void)startVoiceRecognition
{
    //通知主线程刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        //回调或者说是通知主线程刷新，
        
        [[VoiceRecognition sharedInstance] startVoiceRecognition];
        [[VoiceRecognition sharedInstance] monitorVoiceRecognition:^(id data, id status)
         {
            //            NSLog(@"百度语音识别============>%@==========>%@",data,status);
             
             UITextField* searchBar =   self.searchBarController.searchBarView.textField;
             
            if([status intValue]==5)
            {
                searchBar.placeholder = data;
                return;
            }
            
          //  [UMengShare event:CK_VOICESEARCH acc:1];
            
            searchBar.placeholder = @"全球电商搜索...";
            _strSearchTerm = data;
            
            [UIView animateWithDuration:0.5f animations:^{
                searchBar.text = data;
            } completion:^(BOOL finished)
             {
             }];
        }];
        
    });
    
    
    
    
}
- (void)finishRecord:(id)sender
{
    //通知主线程刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        //回调或者说是通知主线程刷新，
        
        
        
        [[VoiceRecognition sharedInstance] finishRecord];
        
        
    });
}
-(void)cancelVoiceRecognition
{
    //通知主线程刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        //回调或者说是通知主线程刷新，
        
        [[VoiceRecognition sharedInstance] cancelVoiceRecognition];
        
    });
}


- (void) createVoiceButton
{
    if(_recordButton == nil)
    {
        _recordButton = [UIButton buttonWithType:UIButtonTypeCustom];

        _recordButton.layer.shadowColor = [UIColor blackColor].CGColor;
        _recordButton.layer.shadowOffset = CGSizeMake(-1,-1);
        
        _recordButton.layer.shadowOpacity = 0.2;// 0.6;
        _recordButton.layer.shadowRadius = 0.5;//阴影半径，默认3
        
        [_recordButton setBackgroundImage:[UIImage imageNamed:@"mic.png"] forState:UIControlStateNormal];
        [_recordButton setBackgroundImage:[UIImage imageNamed:@"mic_recording.png"] forState:UIControlStateHighlighted];
        
        _recordButton.tag = 1;
        _recordButton.frame =  CGRectMake(DEVICE_WIDTH,// - 48,
                                          DEVICE_HEIGHT,
                                          //- keyboardSize.height,// - 48,
                                          1, 1);
 
        [_recordButton addTarget:self action:@selector(recordPressing) forControlEvents:UIControlEventTouchDown];
        [_recordButton addTarget:self action:@selector(recordPressed) forControlEvents:UIControlEventTouchUpInside];
        
        [_recordButton addTarget:self action:@selector(recordPressed) forControlEvents:UIControlEventTouchUpOutside];
    
        [self.view addSubview: _recordButton];
    }
}


- (void) recordPressing
{
    
  //  [self backLookRight];
    
    [UIView animateWithDuration:0.2f animations:^
     {
         _recordButton.frame =
                CGRectMake(_recordButton.frame.origin.x - 56*1,
                           _recordButton.frame.origin.y - 48*1,
                           56*2,
                           48*2);
         _recordButton.layer.shadowOpacity = 1;//0.9;// 0.6;
         
     }
     completion:^(BOOL finished)
     {
         UITextField* searchBar =   self.searchBarController.searchBarView.textField;
         searchBar.placeholder = @"录音中...";//searchBar.text;
         searchBar.text = @"";
         _strSearchTerm = searchBar.text;
 
     }
     ];
    [self startVoiceRecognition];
}


- (void) recordPressed
{
    [self finishRecord:nil];
    [UIView animateWithDuration:0.3f animations:^
     {
         _recordButton.frame = CGRectMake(_recordButton.frame.origin.x + 56*1, _recordButton.frame.origin.y + 48*1, 56, 48);
         _recordButton.layer.shadowOpacity = 0.2;// 0.6;
         
     }completion:^(BOOL finished)
     {
         
     }
     ];
    
    
}


- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    
    
    
    NSDictionary *userInfo = notification.userInfo;
    
    // 键盘的frame
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGSize keyboardSize = keyboardF.size;
    
    [self createVoiceButton];
    
    
    [self.view bringSubviewToFront:_recordButton];
    
    if( !_recordButton )
        return;
    
    _recordButton.frame =CGRectMake(self.view.bounds.size.width - 56,
                                    self.view.bounds.size.height- keyboardSize.height - 48,
                                    56,
                                    48);
    
    
    if(_recordButton.tag == 1)
    {
        
        _recordButton.tag = 0;
        
        [UIView animateWithDuration:0.2f animations:^
         {
             _recordButton.transform = CGAffineTransformMakeScale(1.5, 1.5);
         }
                         completion:^(BOOL finished) {
                             
                             [UIView beginAnimations:nil context:nil];
                             [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
                             [UIView setAnimationDuration:0.2];
                             [UIView setAnimationRepeatCount:1.5];
                             
                             [UIView setAnimationRepeatAutoreverses:YES];
                             [UIView setAnimationBeginsFromCurrentState:YES];
                             
                             
                             _recordButton.transform = CGAffineTransformIdentity;
                             [UIView commitAnimations];
                         }];
        
    }
    
    
    
    _historyTableView.frame = CGRectMake(0,
                                         hightAuto(65),
                                         DEVICE_WIDTH, DEVICE_HEIGHT - keyboardSize.height - hightAuto(65));
    
    
    
}


/**
 * 键盘的frame发生改变时调用（显示、隐藏等）
 */
- (void)keyboardWasHidden:(NSNotification *)notification
{
    
    if(_recordButton)
    {
        _recordButton.frame =CGRectMake(self.view.bounds.size.width - 56, self.view.bounds.size.height- 48, 56, 48);
    }
    
    
}



- (void) registerForKeyboardNotifications
{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];//在这里注册通知
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];

}


- (void) removeForKeyboardNotifications
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

    
}


///////////////////

- (void) viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =UIColorFromRGB(0xf5f5f5);
    self.navigationController.navigationBarHidden=YES;
    // Do any additional setup after loading the view.
    [UMengShare event:CK_SEARCH acc:1];
    //取消所有请求
    [[SVHTTPClient sharedClient] cancelAllRequests];
    if (!_suggArray) {
        _suggArray =[[NSMutableArray alloc] init];
    }
    if (!_resultArray) {
        _resultArray =[[NSMutableArray alloc] init];
    }
    if (!_dcTaobaoSku) {
        _dcTaobaoSku =[NSMutableDictionary dictionary];
    }
    
    [self registerForKeyboardNotifications];
    
    _process=0.0;
    _totoalProgress=0.0;
//    _nShowMoreData =-1;
    _strNameExpanded = @"";
    

    [self createVoiceButton];
    
    [self initSearch];
    [self initUI];
    
    
    
    _historyTableView = [[HotwordsHistoryTableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _historyTableView.delegate = _historyTableView;
    _historyTableView.dataSource = _historyTableView;
    _historyTableView.backgroundColor = [UIColor whiteColor];
    _historyTableView.frame = CGRectMake(0,
                                         hightAuto(65),
                                         DEVICE_WIDTH, DEVICE_HEIGHT - hightAuto(65));
    [self.view addSubview:_historyTableView];
    
    __weak typeof (self) wSelf = self;
    
    [_historyTableView setCallback:^(int type, NSString *str) {
        if(type == 1)
        {
            //打开网站
            
            WebViewController *shaidanweb =[[WebViewController alloc] init];
            shaidanweb.titlestr= @"search";
            shaidanweb.urlstr=str;
            [wSelf.navigationController pushViewController:shaidanweb animated:YES];
            shaidanweb=nil;
            
        }
        else if(type == 2)
        {
            //搜索关键词
            [wSelf searchKey:str];
        }
    }];
    
    if([self.strSearchTerm length] > 0)
    {
        //填入默认的搜索关键字
        [self searchKey:self.strSearchTerm];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    //取消所有请求
    [[SVHTTPClient sharedClient] cancelAllRequests];
}
-(void)dealloc
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    //取消所有请求
    [[SVHTTPClient sharedClient] cancelAllRequests];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if(_historyTableView)
    {
        [_historyTableView removeFromSuperview];
        _historyTableView = nil;
    }
    self.strSearchTerm = nil;
    
    self.strSearchTermEnglish = nil;

    
    if(self.searchBarController.searchBarView.textField.isFirstResponder)
        [self.searchBarController.searchBarView.textField resignFirstResponder];
    
    if(_suggArray)
    {
        [_suggArray removeAllObjects];
        _suggArray = nil;
    }
    
    if(_recordButton)
    {
        [_recordButton removeFromSuperview];
        _recordButton = nil;
    }
    
    if(_resultArray)
    {
        [_resultArray removeAllObjects];
        _resultArray = nil;
    }
    
    if(_dcTaobaoSku)
    {
        [_dcTaobaoSku removeAllObjects];
        _dcTaobaoSku = nil;
    }
    
    
    if(_baseData)
    {
        //   [_baseData removeAllObjects];
        _baseData = nil;
    }
    
    if(_recommendURL)
    {
        _recommendURL = nil;
    }
    
    if(_footerGifView)
    {
        [_footerGifView removeFromSuperview];
        _footerGifView = nil;
    }
    
    if(_footerIntroLabel)
    {
        [_footerIntroLabel removeFromSuperview];
        _footerIntroLabel = nil;
    }
    
    if(_footerView)
    {
        [_footerView removeFromSuperview];
        _footerView = nil;
    }
    
    if(_tbView)
    {
        [_tbView removeFromSuperview];
        _tbView = nil;
    }
    
    
    self.strSearchTerm = nil;
    
    //隐藏进度
    self.progress=0.0;

    self.searchBarController.active =NO;
    self.searchBar=nil;
    self.searchBarController.delegate= nil;
    self.searchBarController=nil;
    
    
    DLog(@"%s", __PRETTY_FUNCTION__);
}
//////////////////////////////////////////////////////////////////////////////////
// 自动提醒数据
//////////////////////////////////////////////////////////////////////////////////
-(void)initSearch
{

   //
    _recommendURL = [ZShare sharedInstance].suggParamsArray;
    _baseData =[ZShare sharedInstance].searchParamsArray;
    self.process=0;
    self.totoalProgress =[_baseData count];
    
    UIView *headView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,hightAuto(65))];
    headView.backgroundColor=[UIColor clearColor];
    UIImageView *backView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, hightAuto(65))];
    backView.image =[UIImage imageNamed:@"titile_bg.png"];
    [headView addSubview:backView];
    backView=nil;
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 20+(65-20-25)/2, 30, 25);
    backButton.tag =0;
    [backButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(clickNavEvent) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:backButton];
    
    if (self.searchBar) {
        [self.searchBar removeFromSuperview];
        self.searchBar=nil;
    }
    self.searchBar =[[MDSearchBar alloc] initWithFrame:CGRectMake(30,(hightAuto(65)-28)/2+10, self.view.frame.size.width-30, 28)];
    [headView addSubview:self.searchBar];
    
    if (self.searchBarController)
    {
        self.searchBarController.delegate= nil;
        self.searchBarController.active =NO;
        self.searchBarController=nil;
    }
    self.searchBarController = [[MDSearchBarController alloc] init];
    self.searchBarController.delegate= self;
    self.searchBarController.searchBarView.frame = self.searchBar.frame;
    
    
    [self.searchBar.superview addSubview:self.searchBarController.searchBarView];
    [self.searchBar removeFromSuperview];
    self.searchBar = self.searchBarController.searchBarView;
    
    self.searchBarController.active = NO;//YES;
    
    if([self.strSearchTerm length] == 0)
    {
        [self.searchBarController.searchBarView.textField becomeFirstResponder];
    }
   
    self.progressBar.frame =CGRectMake(0, hightAuto(64), 0,1);
    [headView addSubview:self.progressBar];
    [self.view addSubview:headView];
    
}
-(void)clickNavEvent
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    //取消所有请求
    [[SVHTTPClient sharedClient] cancelAllRequests];
    self.searchBarController.active =NO;
    [_suggArray removeAllObjects];
    [self.searchBarController.searchBarView.textField resignFirstResponder];
    self.searchBar=nil;
    self.searchBarController.delegate= nil;
    self.searchBarController=nil;
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)searchBar:(MDSearchBarController *)searchBarController searchWithText:(NSString *)text{
    //
    if(_strSearchTerm == text)
    {
        return;
    }
    
    _strSearchTerm = text;

    [self suggestSearch:text];
    if([text length] == 0)
    {
        self.searchBarController.active =NO;
        self.searchBarController.searchBarView.textField.text = @"";
        [self.suggArray removeAllObjects];
        [self.searchBarController reloadData];
        //   return;
    }
}
-(void)searchBar:(MDSearchBarController *)searchBarController searchWithActive:(BOOL)active
{
   
     [self.searchBarController reloadData];
}
-(void)searchBar:(MDSearchBarController *)searchBarController searchWithKeyWord:(NSString *)isSearch
{
    self.searchBarController.active =NO;
    [self searchKey:isSearch];
}
-(void)cancleSearch:(MDSearchBarController *)searchBarController
{
    //隐藏进度
    self.progress=0.0;
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    //取消所有请求
    [[SVHTTPClient sharedClient] cancelAllRequests];
    self.searchBarController.active =NO;
    
    [_suggArray removeAllObjects];
    [self.searchBarController.searchBarView.textField resignFirstResponder];
    self.searchBar=nil;
    self.searchBarController.delegate= nil;
    self.searchBarController=nil;
    [self.navigationController popViewControllerAnimated:YES];
}



-(void)suggestSearch:(NSString *)key
{
    if (key==nil||key.length==0)
    {
//        key=@"";
        return;
    }

    [_suggArray removeAllObjects];
    __weak typeof (self) wSelf = self;
    NSString* strURL =[_recommendURL stringForKey:@"crawl_url" withDefaultValue:@""];
    if([strURL length] == 0)
        return;
    strURL = [strURL stringByReplacingOccurrencesOfString:@"###keywords###" withString:key];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[SVHTTPClient sharedClient] GET:strURL parameters:nil completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error) {
        if (response==nil || error !=nil)
        {
            [wSelf.suggArray removeAllObjects];
            [wSelf.searchBarController reloadData];
            return;
        }
        NSDictionary *dc = response;
        if (dc &&[dc isKindOfClass:[NSDictionary class]])
        {
            NSArray* resutl =[dc arrayObjectForKey:@"result"];
            if (resutl&&[resutl isKindOfClass:[NSArray class]]) {
                
                [wSelf.suggArray removeAllObjects];
                [resutl enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
                 {
                     if (obj && [obj isKindOfClass:[NSArray class]])
                     {
                         NSArray *objj = (NSArray*)obj;
                         if (objj.count>0)
                         {
                             [wSelf.suggArray addObject:[objj objectAtIndex:0]];
                         }
                         
                     }
                 }];
                
            }
            if (wSelf.searchBarController.searchBarView.textField.text.length==0) {
                [wSelf.suggArray removeAllObjects];
            }
            if([wSelf.suggArray count] > 0)
            {
                if(wSelf.searchBarController.active == NO)
                    wSelf.searchBarController.active = YES;
           //     [wSelf.view bringSubviewToFront: wSelf.recordButton];
            }
            [wSelf.searchBarController reloadData];
        }
    }];
    
}
//////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////
//=======================================
//初始化ui
//=======================================
- (void)setProgress:(CGFloat)progress
{
    _progress = MAX(0.0, MIN(1.0, progress));
    if (_progress<=0) {
        self.progressBar.backgroundColor=UIColorFromRGB(0xe5e5e5);
        self.progressBar.frame = CGRectMake(0,  hightAuto(64), CGRectGetWidth(self.view.bounds), 1);
    }else
    {
        self.progressBar.backgroundColor = [UIColor blackColor];//UIColorFromRGB(0xCE0202);
        self.progressBar.frame = CGRectMake(0,  hightAuto(64), _progress * CGRectGetWidth(self.view.bounds), 1);
    }
}
-(UIView*)progressBar
{
    if (!_progressBar) {
        _progressBar = [[UIView alloc] initWithFrame:CGRectMake(0,self.view.frame.size.height + 15,0, 1)];
        _progressBar.opaque = YES;
        _progressBar.backgroundColor = [UIColor blackColor];//UIColorFromRGB(0xCE0202);
    }
    return _progressBar;
    
}

- (void) updateProgress
{
    [UIView animateWithDuration:0.2f animations:^{
        self.progress = self.process/self.totoalProgress;
    } completion:^(BOOL finished) {
        
    }];
    
    
    //  NSLog(@"---------->%f",self.process);
    if (self.progress>=1)
    {
        self.progress=0.0;
        self.tbView.tableFooterView = [self footerView:@"搜索完毕."];
    }
}


-(UIView*)footerView:(NSString*)msg
{
    if (!_footerView) {
        _footerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 210)];
        _footerView.backgroundColor=[UIColor whiteColor];
    }
    if (self.process>=self.totoalProgress && self.totoalProgress != 0)
    {
        [self.footerGifView removeFromSuperview];
        _footerView.frame =CGRectMake(0, 0, self.view.frame.size.width, 90);
        [_footerView addSubview:self.footerIntroLabel];
        self.footerIntroLabel.text = msg;
    }else
    {
        [self.footerIntroLabel removeFromSuperview];
        _footerView.frame =CGRectMake(0, 0, self.view.frame.size.width, 210);
        [_footerView addSubview:self.footerGifView];
    }
    return _footerView;
}
-(UIImageView*)footerGifView
{
    if(!_footerGifView)
    {
        _footerGifView =[[UIImageView alloc] initWithFrame:CGRectMake((DEVICE_WIDTH-350)/2, 0, 350, 210)];
        _footerGifView.contentMode = UIViewContentModeScaleAspectFit;
        AppDelegate *app = [[UIApplication sharedApplication]delegate];
        _footerGifView.image = [app imgLoading];//todo: bug, 这个loading图片哪里去了？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？
        
    }
    return _footerGifView;
}
-(UILabel*)footerIntroLabel
{
    if (!_footerIntroLabel) {
        _footerIntroLabel =[[UILabel alloc] initWithFrame:CGRectMake(0, 25, DEVICE_WIDTH, 20)];
        _footerIntroLabel.backgroundColor = [UIColor clearColor];
        _footerIntroLabel.textColor = UIColorFromRGB(0xbfbfbf);
        _footerIntroLabel.textAlignment = NSTextAlignmentCenter;
        _footerIntroLabel.font = FONT(16);
        _footerIntroLabel.numberOfLines=0;
    }
    return _footerIntroLabel;
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap
{
    // if([strBrand length] == 0)
    
    if([self.searchBarController.searchBarView.textField isFirstResponder])
    {
        [self.searchBarController.searchBarView.textField resignFirstResponder];
    }
}


//
-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, hightAuto(65), self.view.frame.size.width, self.view.frame.size.height-hightAuto(65)) style:UITableViewStyleGrouped]; //UITableViewStylePlain
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor = [UIColor whiteColor];
    _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tbView.showsVerticalScrollIndicator = NO;
  //  _tbView.bounces = NO;
    
    [self.view addSubview:_tbView];
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [_tbView addGestureRecognizer:tapGestureRecognizer];
    tapGestureRecognizer=nil;
    
    
    _tableProgressBar = [[SearchProgressTableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableProgressBar.delegate = _tableProgressBar;
    _tableProgressBar.dataSource = _tableProgressBar;
    _tableProgressBar.backgroundColor = [UIColor whiteColor];
    _tableProgressBar.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableProgressBar.transform = CGAffineTransformMakeRotation(-M_PI / 2);
    
    
    _tableProgressBar.frame = CGRectMake(0, hightAuto(65), DEVICE_WIDTH, TABLE_TOP_INSET);
    _tableProgressBar.showsVerticalScrollIndicator = NO;
    _tableProgressBar.scrollsToTop = NO;
    _tableProgressBar.tag = 1;
  //  _tableProgressBar.bounces = NO;
    [self.view addSubview:_tableProgressBar];
    
    __weak typeof (self) wSelf = self;
    [_tableProgressBar setCallback:^(int type, NSString *str)
    {
        //11111
        NSLog(@"%@",str);
        if(self.resultArray == nil)
            return ;
        
        for(int i = 0; i < wSelf.resultArray.count; i++)
        {

            id obj = [wSelf.resultArray objectAtIndex:i];
            if (obj&& [obj isKindOfClass:[NSString class]])
            {
                continue;
            }
            else if (obj&& [obj isKindOfClass:[NSDictionary class]])
            {
                NSString *name =[obj stringForKey:@"name" withDefaultValue:@""];
                
                if([name isEqual:str])
                {
                    
                    NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:i];
                    [wSelf.tbView scrollToRowAtIndexPath:lastRow
                                                atScrollPosition:UITableViewScrollPositionTop
                                                        animated:YES];

                    
                    break;
                }
            }
        }

    }];
    
    
    if(_tableProgressBar)
    {
        [_tableProgressBar setData:[ZShare sharedInstance].searchParamsArray reset:YES];
    }
    
    
//    _tableProgressBar.baseData = _baseData;
    
    _tbView.contentInset = UIEdgeInsetsMake(TABLE_TOP_INSET, 0, 0, 0);
    
 //   [_tableProgressBar reloadData];
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView==_tbView) {
        return self.resultArray.count;
    }else
    {
        return 1;
        
    }
    return 0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView==_tbView)
    {
        if(section > self.resultArray.count)
        {
            return 0;
        }
        
        id obj = [self.resultArray objectAtIndex:section];
        if (obj && [obj isKindOfClass:[NSString class]])
        {
            return 1;
        }
        else if (obj&& [obj isKindOfClass:[NSDictionary class]])
        {
            //if(_nShowMoreData == section)
            //NSString* strName = [obj objectForKey:@"name"];
            NSString *name =[obj stringForKey:@"name" withDefaultValue:@""];
            if([_strNameExpanded isEqual:name])
            {
                NSArray* shop_list = [obj arrayObjectForKey:@"data"];
                if (shop_list && [shop_list isKindOfClass:[NSArray class]])
                {
                    return shop_list.count + 1;
                }
            }

            NSArray* shop_list = [obj arrayObjectForKey:@"data"];
            if (shop_list && [shop_list isKindOfClass:[NSArray class]])
            {
                NSString* strLimitCount = [obj stringForKey:@"data_limit" withDefaultValue:@""];
                if(strLimitCount && strLimitCount.length > 0 && [strLimitCount integerValue] < shop_list.count)
                {
                    return [strLimitCount integerValue];
                }
                else
                {
                
                    return shop_list.count;
                }
            }
            
            
        }
    }else{

        return self.suggArray.count;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
    view.tintColor = [UIColor clearColor];
}


- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.tintColor = [UIColor clearColor];
    
    // Text Color
    //   UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    //   [header.textLabel setTextColor:[UIColor whiteColor]];
    
    // Another way to set the background color
    // Note: does not preserve gradient effect of original header
    // header.contentView.backgroundColor = [UIColor blackColor];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView==_tbView)
    {
        if(section>self.resultArray.count)
        {
            return 0.01;
        }
        id obj = [self.resultArray objectAtIndex:section];
        if (obj && [obj isKindOfClass:[NSString class]])
        {
            return 10;
        }
        else if (obj && [obj isKindOfClass:[NSDictionary class]])
        {
            NSString *keyv =[obj stringForKey:@"key" withDefaultValue:@""];
            if ([keyv isEqualToString:@"baidubk"])
            {
                return 10;//10
            }
            
            return 50;
        }
    }
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (tableView==_tbView)
    {
        if(section>self.resultArray.count)
        {
            return 0.01;
        }
        id obj = [self.resultArray objectAtIndex:section];
        if (obj&& [obj isKindOfClass:[NSString class]])
        {
            return 0.01;
        }
        else if (obj&& [obj isKindOfClass:[NSDictionary class]])
        {
            return 10;
        }
    }
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==_tbView)
    {
        if(indexPath.section>self.resultArray.count)
        {
            return 0;
        }
        
        id obj = [self.resultArray objectAtIndex:indexPath.section];
        if (obj && [obj isKindOfClass:[NSString class]])
        {
            return [NiubiTagCell returnCellHeight:self.suggArray];
        }
        else if (obj && [obj isKindOfClass:[NSDictionary class]])
        {
            NSArray* data = [obj arrayObjectForKey:@"data"];
            if(data && [data isKindOfClass:[NSArray class]] && [data count] > 0)
            {
                if(indexPath.row >= [data count])
                {
                    return 60;
                }
            }
            
            
            NSString *keyv =[obj stringForKey:@"key" withDefaultValue:@""];
            if ([keyv isEqualToString:@"baidubk"])
            {
                return [BaikeCell returnCellHeight:[data objectAtIndex:indexPath.row] ];
            }
            else if ([keyv isEqualToString:@"baidu"])
            {
                return 32;
            }else if ([keyv isEqualToString:@"danpin"] )
            {
                return [DanpinCell returnCellHeight:nil];
            }else if ([keyv isEqualToString:@"mgpyh"])
            {
                id obj = [self.resultArray objectAtIndex:indexPath.section];
                 NSArray* shop_list = [obj arrayObjectForKey:@"data"];
                if (shop_list && [shop_list isKindOfClass:[NSArray class]])
                {
                    if (shop_list.count == 0 || shop_list.count < indexPath.row)
                    {
                        
                        return 0;
                    }
                    NSDictionary *shop = [shop_list objectAtIndex:indexPath.row];
                     return [MgpyhCell returnCellHeight:shop];
                }
                return 0;
                
            }else
            {
                return [BuyFromCell returnCellHeight:nil];
            }
        }
    }else
    {
         return 40;
       
    }
    return 0;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView==_tbView)
    {
     
        if(section>self.resultArray.count)
        {
            return nil;
        }
        UIView *sectionView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 50)];
        sectionView.backgroundColor =[UIColor whiteColor];
        sectionView.alpha = 0.9f;
        id obj = [self.resultArray objectAtIndex:section];
        if (obj&& [obj isKindOfClass:[NSString class]])
        {
            return nil;
        }else if (obj&& [obj isKindOfClass:[NSDictionary class]])
        {
            NSString *keyv =[obj stringForKey:@"key" withDefaultValue:@""];
            if ([keyv isEqualToString:@"baidubk"])
            {
                return nil;
            }
            
            NSString *name =[obj stringForKey:@"name" withDefaultValue:@""];
            if ([name isEqualToString:@"推荐购买"])//不要用字符串判断，云端输出个类型不就可以了。
            {
                UILabel *tagValue =[[UILabel alloc] initWithFrame:CGRectMake(PHOTO_FRAME_WIDTH,(50-30)/2, tableView.frame.size.width, 30)];
                tagValue.backgroundColor = [UIColor clearColor];
                tagValue.textColor = UIColorFromRGB(0x000000);
                tagValue.textAlignment = NSTextAlignmentLeft;
                tagValue.font = FONT(15);
                tagValue.text =name;
                [sectionView addSubview:tagValue];
                tagValue=nil;
                UIView *lineview =[[UIView alloc] initWithFrame:CGRectMake(0, 49.5, tableView.frame.size.width, 0.5)];
                lineview.backgroundColor=UIColorFromRGB(0xe5e5e5);
                [sectionView addSubview:lineview];
                lineview=nil;
                
                return sectionView;
            }else
            {
                
                UILabel *tagValue =[[UILabel alloc] initWithFrame:CGRectMake(PHOTO_FRAME_WIDTH,(50-30)/2, tableView.frame.size.width, 30)];
                tagValue.backgroundColor = [UIColor clearColor];
                tagValue.textColor = UIColorFromRGB(0x000000);
                tagValue.textAlignment = NSTextAlignmentLeft;
                tagValue.font = FONT(15);
                tagValue.text =name;
                [sectionView addSubview:tagValue];
                
                //
                NSString *imag =[obj stringForKey:@"img" withDefaultValue:@""];
                if (imag.length>0) {
                    UIImageView *titleIcon =[[UIImageView alloc] initWithFrame:CGRectMake(PHOTO_FRAME_WIDTH,(50-36)/2, 70, 36)];
                    titleIcon.contentMode = UIViewContentModeScaleAspectFit;
                    [titleIcon sd_setImageWithURL:[NSURL URLWithString:imag] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
                     {
                         if (image) {
                             [tagValue removeFromSuperview];
                         }
                     }];
                    [sectionView addSubview:titleIcon];
                    titleIcon=nil;
                }
                //
                UIButton *buyBtn =[UIButton buttonWithType:UIButtonTypeCustom];
                buyBtn.tag =section;
                [buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                buyBtn.backgroundColor = [UIColor lightGrayColor];
                buyBtn.frame =CGRectMake(DEVICE_WIDTH-PHOTO_FRAME_WIDTH - 50,(50-10)/2, 50, 10);
                buyBtn.titleLabel.font =FONT(12);
                buyBtn.layer.cornerRadius=10;
               
                NSString* strAvgPrice =[obj stringForKey:@"avg_price" withDefaultValue:@""];
                float fPrice = [strAvgPrice floatValue];
                if(fPrice > 0)
                {   strAvgPrice = [NSString stringWithFormat:@" 均价: ¥%.0f ▽ ", ceilf(fPrice)];
                 } else {
                    strAvgPrice = @" 更多... ";
                }
                
                [buyBtn setTitle:strAvgPrice forState:UIControlStateNormal];
                [buyBtn sizeToFit];
                
                //NSString *name =[obj stringForKey:@"name" withDefaultValue:@""];
                if([_strNameExpanded isEqual:name])
                {
                //if(_nShowMoreData == section)
                //{
                    strAvgPrice = @" 收起 △ ";
                    buyBtn.backgroundColor = [UIColor colorWithRed:0.992 green:0.275 blue:0.020 alpha:1];
                    [buyBtn setTitle:strAvgPrice forState:UIControlStateNormal];
                }
    
                buyBtn.frame =CGRectMake(DEVICE_WIDTH-PHOTO_FRAME_WIDTH*1.5 - buyBtn.frame.size.width-5,(50-20)/2, buyBtn.frame.size.width+10, 20);
                [buyBtn addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
                [sectionView addSubview:buyBtn];
                
                
                UIView *lineview =[[UIView alloc] initWithFrame:CGRectMake(0, 49.5f, tableView.frame.size.width, 0.5)];
                lineview.backgroundColor=UIColorFromRGB(0xe5e5e5);
                [sectionView addSubview:lineview];
                lineview=nil;
                
                return sectionView;
            }
            return nil;
        }

    }
    return nil;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if(scrollView == _tbView)
    {
        //用户在滚动搜索结果页面，取消键盘。
        if([self.searchBarController.searchBarView.textField isFirstResponder])
            [self.searchBarController.searchBarView.textField resignFirstResponder];
        
        BOOL bDragging = scrollView.dragging;
        
        
        float currentPostion = scrollView.contentOffset.y;
        if ((currentPostion - _lastOffsetY) > TABLE_TOP_INSET && currentPostion > TABLE_TOP_INSET)
        {
            _lastOffsetY = currentPostion;
            
            
            if(bDragging && _tableProgressBar.tag != 0)
            {
                _tableProgressBar.tag = 0;
                
                [UIView animateWithDuration:0.2f animations:^{
                    _tableProgressBar.alpha = 0;
                } completion:^(BOOL finished) {
                    
                }];
             //   _tableProgressBar.hidden = YES;
                NSLog(@"ScrollUp now");
            }
        }
        else if (_lastOffsetY - currentPostion > 5)
        {
            _lastOffsetY = currentPostion;
            
            if(_tableProgressBar.tag != 1)
            {
                _tableProgressBar.tag = 1;
                
                [UIView animateWithDuration:0.2f animations:^{
                    _tableProgressBar.alpha = 1;
                } completion:^(BOOL finished) {
                    
                }];
                
                NSLog(@"ScrollDown now");
            }
        }
    
    }
}

- (UITableViewCell*)getErrorcell:(UITableView*)tableView
{
    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"ErrorEmptyCell"];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ErrorEmptyCell"];
    }
    return  cell;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  //  UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
    if (tableView==_tbView)
    {
        if (indexPath.section>self.resultArray.count)
        {
            return [self getErrorcell:tableView];
        }
        id obj = [self.resultArray objectAtIndex:indexPath.section];
        if (obj&& [obj isKindOfClass:[NSString class]])
        {
            NiubiTagCell * cell = (NiubiTagCell*) [tableView  dequeueReusableCellWithIdentifier:@"niubiSearchVCTags"];
            if(cell == nil)
            {
                cell = [[NiubiTagCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"niubiSearchVCTags"];
                cell.backgroundColor=[UIColor clearColor];
             //   cell.selectionStyle = UITableViewCellSelectionStyleNone;
                __weak typeof (self) wSelf = self;
                [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath)
                 {
                     [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
                 }];
            }
            [cell showInfo:self.suggArray indexPath:indexPath];
            return cell;
        }
        else if (obj&& [obj isKindOfClass:[NSDictionary class]])
        {
            NSString *keyv =[obj stringForKey:@"key" withDefaultValue:@""];
            
            if ([keyv isEqualToString:@"baidu"])
            {
                
                BaiduCell * cell = (BaiduCell*) [tableView  dequeueReusableCellWithIdentifier:@"BaiduCell"];
                if(cell == nil)
                {
                    cell = [[BaiduCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BaiduCell"];
                    cell.backgroundColor=[UIColor whiteColor];
                //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    
                }
                
                NSArray* array = [obj arrayObjectForKey:@"data"];

                if(array ==nil || indexPath.row >= [array count])
                    return cell;
                
                NSDictionary* dcTitleHref = [array objectAtIndex:indexPath.row];
                NSString *str =[dcTitleHref stringForKey:@"title" withDefaultValue:@""];
                if (str.length>0) {
                    [cell.title setText:str afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString  *(NSMutableAttributedString *attributedString)
                     {
                         
                         [attributedString addAttribute:NSFontAttributeName value:FONT(13) range:NSMakeRange(0,[attributedString length])];
                         
                         //设置字体颜色
                         [attributedString addAttribute:(id)kCTForegroundColorAttributeName value:TITLE_COLOR range:NSMakeRange(0,[attributedString length])];
                         
                         
                         NSArray* words = [dcTitleHref arrayObjectForKey:@"words"];
                         if(words && [words isKindOfClass:[NSArray class]])
                         {
                             
                             for(int i = 0; i < [words count]; i++)
                             {
                                 
                                 
                                 NSString* strWord = [words objectAtIndex:i];
                                 NSRange range = [[attributedString string] rangeOfString:strWord options:NSCaseInsensitiveSearch];
                                 
                                 if (range.location != NSNotFound)
                                 {
                                     [attributedString addAttribute:(id)kCTForegroundColorAttributeName value:HILIGHT_COLOR range:range];
                                     
                                 }
                                 
                                 
                             }
                         }
                         //       CFRelease(helveticaBold);
                         
                         return attributedString;
                         
                     }];
                }
               
                [cell showInfo:dcTitleHref key:keyv indexPath:indexPath];
                
                return cell;
                
            }
            else if ([keyv isEqualToString:@"baidubk"])
            {
                BaikeCell *cell = (BaikeCell*)[tableView  dequeueReusableCellWithIdentifier:@"BaikeCell"];
                if(cell == nil)
                {
                    cell = [[BaikeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BaikeCell"];
                    cell.backgroundColor=[UIColor whiteColor];
                //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    
                }
                NSArray* shop_list =[obj arrayObjectForKey:@"data"];
                if (shop_list && [shop_list isKindOfClass:[NSArray class]])
                {
                    if (shop_list.count==0||shop_list.count<indexPath.row)
                    {
                        return cell;
                    }
                    NSString *isHave =@"1";
                    if (indexPath.row==[shop_list count]-1)
                    {
                        isHave =@"0";
                    }
                    if(indexPath.row>shop_list.count)
                    {
                        return cell;
                    }
                    NSDictionary *shop = [shop_list objectAtIndex:indexPath.row];
                    NSString *name =[obj stringForKey:@"name" withDefaultValue:@""];
                    [cell showInfo:shop other:isHave key:name indexPath:indexPath];
                }
                return cell;
            }
            else
            {
                NSArray* shop_list = [obj arrayObjectForKey:@"data"];
                if (shop_list && [shop_list isKindOfClass:[NSArray class]])
                {
                    
                    if( indexPath.row >= shop_list.count)
                    {
                        // NSLog(@"更多...");
                        UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@"goWebsiteCell"];
                        if(cell == nil)
                        {
                            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"goWebsiteCell"];
                            cell.backgroundColor=[UIColor clearColor];
                        //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                            
                            cell.textLabel.textAlignment = NSTextAlignmentRight;
                            cell.textLabel.textColor = [UIColor grayColor];
                            cell.textLabel.font = FONT(15);
                            
                            UIView *lineview =[[UIView alloc] initWithFrame:CGRectMake(0, 59.5, tableView.frame.size.width, 0.5)];
                            lineview.backgroundColor=UIColorFromRGB(0xe5e5e5);
                            [cell addSubview:lineview];
                            lineview=nil;
                            
                            
                        }
                        
                        
                        NSString* strName = [obj stringForKey:@"name" withDefaultValue:@""];
                        cell.textLabel.text = [NSString stringWithFormat:@"更多%@的商品...", strName];
                        
                        
                        return cell;
                    }
                }
                
                if ([keyv isEqualToString:@"danpin"] )
                {
                    DanpinCell *cell = (DanpinCell*)[tableView  dequeueReusableCellWithIdentifier:@"DanpinCell"];
                    if(cell == nil)
                    {
                        cell = [[DanpinCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DanpinCell"];
                        cell.backgroundColor=[UIColor whiteColor];
                     //   cell.selectionStyle = UITableViewCellSelectionStyleNone;
                        
                    }
                    
                    if (shop_list && [shop_list isKindOfClass:[NSArray class]])
                    {
                        if (shop_list.count == 0 || shop_list.count < indexPath.row)
                        {
                            
                            return cell;
                        }
                        
                        NSString *isHave =@"1";
                        if (indexPath.row==[shop_list count]-1)
                        {
                            isHave =@"0";
                        }
                        if(indexPath.row>shop_list.count)
                        {
                            return cell;
                        }
                        NSDictionary *shop = [shop_list objectAtIndex:indexPath.row];
                        NSString *name =[obj stringForKey:@"name" withDefaultValue:@""];
                        [cell showInfo:shop other:isHave key:name indexPath:indexPath];
                    }
                    return cell;
                }else if ([keyv isEqualToString:@"mgpyh"])
                {
                    MgpyhCell *cell = (MgpyhCell*)[tableView  dequeueReusableCellWithIdentifier:@"MgpyhCell"];
                    if(cell == nil)
                    {
                        cell = [[MgpyhCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MgpyhCell"];
                        cell.backgroundColor=[UIColor whiteColor];
                    }
                    
                    if (shop_list && [shop_list isKindOfClass:[NSArray class]])
                    {
                        if (shop_list.count == 0 || shop_list.count < indexPath.row)
                        {
                            
                            return cell;
                        }
                        
                        NSString *isHave =@"1";
                        if (indexPath.row==[shop_list count]-1)
                        {
                            isHave =@"0";
                        }
                        if(indexPath.row>shop_list.count)
                        {
                            return cell;
                        }
                        NSDictionary *shop = [shop_list objectAtIndex:indexPath.row];
                        NSString *name =[obj stringForKey:@"name" withDefaultValue:@""];
                        [cell showInfo:shop other:isHave key:name indexPath:indexPath];
                    }
                    return cell;
                }else
                {
                    BuyFromCell *cell = (BuyFromCell*)[tableView  dequeueReusableCellWithIdentifier:@"BuyFromCell"];
                    if(cell == nil)
                    {
                        cell = [[BuyFromCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BuyFromCell"];
                        cell.backgroundColor=[UIColor whiteColor];
                     //   cell.selectionStyle = UITableViewCellSelectionStyleNone;
                        
                    }
                    
                    if (shop_list && [shop_list isKindOfClass:[NSArray class]])
                    {
                        //    NSMutableArray *array =[NSMutableArray arrayWithArray:shop_list];
                        if (shop_list.count == 0 || shop_list.count < indexPath.row)
                        {
                            
                            return cell;
                        }
                        
                        NSString *isHave =@"1";
                        if (indexPath.row==[shop_list count]-1)
                        {
                            isHave =@"0";
                        }
                        if(indexPath.row>shop_list.count)
                        {
                            return cell;
                        }
                        NSDictionary *shop = [shop_list objectAtIndex:indexPath.row];
                        NSString *name =[obj stringForKey:@"name" withDefaultValue:@""];
                        [cell showInfo:shop other:isHave key:name indexPath:indexPath];
                        
                        
                        
                        cell.skus.text = @"";
                        NSString *strKey =[obj stringForKey:@"key" withDefaultValue:@""];
                        if([strKey isEqual:@"tb"])
                        {
                            //todo : 这个网址应该让服务器端输出， 自己截取商品id非常危险， 淘宝修改url规则就会遇到问题了！
                            NSString* strURL = [shop stringForKey:@"url" withDefaultValue:@""];
                            NSRange rangeBegin = [strURL rangeOfString:@"/i"];
                            NSRange rangeEnd = [strURL rangeOfString:@".htm"];
                            
                            rangeBegin.location += rangeBegin.length;
                            rangeBegin.length = rangeEnd.location - rangeBegin.location;
                            
                            NSString * strID = [strURL substringWithRange:rangeBegin];
                            //以上，应该直接获取strID
                            
                            if(self.dcTaobaoSku && [self.dcTaobaoSku count] > 0)
                            {
                                NSArray* arSku = [self.dcTaobaoSku arrayObjectForKey:strID];
                                
                                NSString * strSkuNames = @"";
                                if(arSku && [arSku isKindOfClass:[NSArray class]])
                                {
                                    
                                    for(int i = 0; i < [arSku count]; i++)
                                    {
                                        NSDictionary * dcSku = [arSku objectAtIndex:i];
                                        if([strSkuNames length] > 0)
                                        {
                                            strSkuNames = [NSString stringWithFormat:@"%@, %@", strSkuNames, [dcSku stringForKey:@"name" withDefaultValue:@""] ];
                                        } else {
                                            strSkuNames = [NSString stringWithFormat:@"%@", [dcSku stringForKey:@"name" withDefaultValue:@""] ];
                                        }
                                    }
                                }
                                cell.skus.text = [NSString stringWithFormat:@"%@", strSkuNames] ;
                            }
                            
                            
                            
                        }
                    }
                    return cell;
                }
               
            }
        }

    }else
    {
        UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@"search_suggestion"];
        //搜索结果的自动完成
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"search_suggestion"];
            cell.contentView.backgroundColor = [UIColor clearColor];
            cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
            cell.selectedBackgroundView.backgroundColor =UIColorFromRGB(0xf4f4f4);
        };

        
        if (self.suggArray.count>0)
        {
            
            if (self == nil || indexPath.row >=self.suggArray.count) {
                return cell;
            }
            
            
            NSString* strText = [self.suggArray objectAtIndex:indexPath.row];
            if(strText && [strText isKindOfClass:[NSString class]])
            {
                cell.textLabel.text = strText;//[NSString stringWithFormat:@"%@",];
                cell.textLabel.font = FONT(12);
            }
            return cell;
        }
        return cell;
    }
    return [self getErrorcell:tableView];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView==_tbView)
    {
        if (indexPath.section>self.resultArray.count) {
            return;
        }
        id obj = [self.resultArray objectAtIndex:indexPath.section];
        if (obj&& [obj isKindOfClass:[NSString class]])
        {
            
        }
        else if (obj&& [obj isKindOfClass:[NSDictionary class]])
        {
            NSArray* shop_list =[obj arrayObjectForKey:@"data"];
            if (shop_list && [shop_list isKindOfClass:[NSArray class]])
            {
                if (indexPath.row>=shop_list.count) {
                    
                    NSString *url =[obj stringForKey:@"url" withDefaultValue:@""];
                    
                    WebViewController *shaidanweb =[[WebViewController alloc] init];
                    shaidanweb.titlestr= @"search";
                    NSString *urltype =[obj stringForKey:@"urltype" withDefaultValue:@""];
                    if ([urltype isEqualToString:@"json"]) {
                        shaidanweb.jsonUrl = url;
                        shaidanweb.urlstr=@"";
                    }else{
                        shaidanweb.jsonUrl = @"";
                        shaidanweb.urlstr=url;
                    }
                    [shaidanweb setForceNewWindow:YES];
                    [self.navigationController pushViewController:shaidanweb animated:YES];
                    shaidanweb=nil;
                    return;
                }else{
                   
                    if (indexPath.row >shop_list.count) {
                        return;
                    }
                    NSDictionary *data = [shop_list objectAtIndex:indexPath.row];
                    
                    
                    NSString *name =[data stringForKey:@"title" withDefaultValue:@""];
                    name = [[name stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"] replaceNullString];
                    NSString *url =[data stringForKey:@"url" withDefaultValue:@""];
                    //todo : baichuan_id\ baichuan_type 应该由服务器端输出，搜索由hqs输出，爆料由tt输出
                    NSString *baichuan_itemid =[data stringForKey:@"baichuan_itemid" withDefaultValue:@""];
                    NSString *baichuan_Type =[data stringForKey:@"baichuan_type" withDefaultValue:@""];
                    if (baichuan_itemid.length>0 && ![baichuan_itemid isEqualToString:@"(null)"]) {
                        [UMengShare event:CK_BUYBAICHUAN acc:1];
                        [[BaiChuanShare sharedInstance] showTaoKeItemDetail:self ItemId:baichuan_itemid itemType:baichuan_Type];
                        return;
                    }

                    WebViewController *shaidanweb =[[WebViewController alloc] init];
                    shaidanweb.titlestr=@"search";
                    
                    NSString *urltype =[data stringForKey:@"urltype" withDefaultValue:@""];
                    if ([urltype isEqualToString:@"json"]) {
                        shaidanweb.jsonUrl = url;
                        shaidanweb.urlstr=@"";
                    }else{
                       shaidanweb.jsonUrl = @"";
                       shaidanweb.urlstr=url;
                    }
                    
                    [self.navigationController pushViewController:shaidanweb animated:YES];
                    shaidanweb=nil;
                    return;
                }
              
            }
        }
    }else{
        if(self.suggArray.count>0)
        {
            if(indexPath.row>=[self.suggArray count])
            {
                return;
            }
            NSString *key =[self.suggArray objectAtIndex:indexPath.row];
            self.searchBarController.active =NO;
            self.tbView.tableFooterView =nil;
            [self.searchBarController.searchBarView.textField resignFirstResponder];
            [self searchKey:key];
            self.searchBarController.searchBarView.textField.text =key;
            
        }
        
    }
    
}
-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    switch (type) {
        case BEventType_taobao:
        {
            
            
        }
            break;
        case BEventType_tag:
        {
            if (obj && [obj isKindOfClass:[NSString class]]) {
                if ([obj isEqualToString:@"更多"]) {
                    [ZShare sharedInstance].lineCount=100;
                    [_tbView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                }else if ([obj isEqualToString:@"收起"]) {
                    [ZShare sharedInstance].lineCount=2;
                    [_tbView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                }
                else
                {
                    [self searchKey:obj];
                    self.searchBarController.searchBarView.textField.text =obj;
                }
                    
            }
            
        }
        default:
            break;
    }
}
//////////////////////////////////////////////////////////////////////////////////
//根据key获取数据
//////////////////////////////////////////////////////////////////////////////////
-(void)tableReload
{
    if (self.suggArray.count>0)
    {
        if (![self.resultArray containsObject:@"tag"])
        {
            [self.resultArray insertObject:@"tag" atIndex:0];
        }
    }
    [_tbView reloadData];
}

-(void)searchKey:(NSString*)key
{
    if([self.searchBarController.searchBarView.textField isFirstResponder])
    {
        [self.searchBarController.searchBarView.textField resignFirstResponder];
    }
   
    //
    self.searchBarController.searchBarView.textField.text =key;
    
    //存历史
    [[SearchShare sharedInstance] saveHistoryForSearch:key];
    
    
    @autoreleasepool
    {
        if (key==nil||key.length==0) {
//            key=@"";
            return;
        }
        
        _strSearchTermEnglish = @"";
        [_resultArray removeAllObjects];
        [_tbView reloadData];
        //取消所有请求
        [[SVHTTPClient sharedClient] cancelAllRequests];
        
        
        if (_baseData.count==0) {
            return;
        }
      //  _nShowMoreData =-1;
        _strNameExpanded = @"";
        self.progress = 0;
        self.process=0.0;
        self.totoalProgress=(CGFloat)_baseData.count;
        self.tbView.tableFooterView = [self footerView:@""];
        
        [self searchKey:key urlData:_baseData resetProgressData:YES];
    }
    
}



-(void)searchKey:(NSString*)key urlData:(NSArray*)urldata resetProgressData:(BOOL) resetProgress
{

    if(_tableProgressBar)
    {
        [_tableProgressBar setData:urldata reset:resetProgress];
    }
    
    if(_historyTableView && _historyTableView.hidden == NO)
    {
        _historyTableView.hidden = YES;
    }
    
        for(id obj in urldata)
        {
            NSDictionary* dc =  obj;
         
            NSString * crawl_url = [dc stringForKey:@"crawl_url" withDefaultValue:@""];
            crawl_url = [crawl_url stringByReplacingOccurrencesOfString:@"###keywords###" withString:key];
            if([crawl_url length] == 0)
                continue;
            
            crawl_url = [crawl_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            NSString* strMethod = [dc stringForKey:@"method" withDefaultValue:@""];
            NSString * strAgent = [dc stringForKey:@"User_Agent" withDefaultValue:@""];
    
            if([strAgent length] > 0)
            {
                [SVHTTPClient sharedClient].userAgent = strAgent;
            }
//           NSLog(@"===========%@",crawl_url);
            __weak typeof (self) wSelf = self;
            if([strMethod isEqual:@"POST"])
            {
                NSString* strPostData = [dc stringForKey:@"post_data" withDefaultValue:@""];
                NSDictionary *params =[NSDictionary dictionaryWithObjectsAndKeys:key,strPostData,nil];
                [[SVHTTPClient sharedClient] POST:crawl_url parameters:params completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error)
                 {
                     [wSelf postResultToDanpin:response dic:dc keyword:key];
                 }
                 ];
            } else {
                
                [[SVHTTPClient sharedClient] GET:crawl_url parameters:nil completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error)
                 {
                     [wSelf postResultToDanpin:response dic:dc keyword:key];
                 }];
            }
            
        }
    
    
}
- (void) postResultToDanpin:(id) response dic:(NSDictionary*)dc keyword:(NSString*) searchTerm
{
    if(response == nil)
    {
        ++self.process;
        [self updateProgress];
        return;
    }
    
    @autoreleasepool
    {
        NSString *post_url =[dc stringForKey:@"post_url" withDefaultValue:@""];
        post_url = [post_url stringByReplacingOccurrencesOfString:@"###keywords###" withString:searchTerm];
        
        //单品数据
        if (post_url.length==0) {
            ++self.process;
            [self updateProgress];
           NSDictionary *dcRes =nil;
            if(response && [response isKindOfClass:[NSDictionary class]])
            {
                dcRes =(NSDictionary*)response;
            }else if (response && [response isKindOfClass:[NSString class]])
            {
                NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
                dcRes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            }else if (response && [response isKindOfClass:[NSData class]])
            {
                dcRes = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil];
            }
            NSArray* data = [dcRes arrayObjectForKey:@"data"];
            if (data && [data isKindOfClass:[NSArray class]])
            {
                NSArray *dataa =(NSArray*)data;
                if (dataa.count>0)
                {
                    [self.resultArray addObject:dcRes];
                }
            }
            
            return;
        }
        
        NSString* strResult=@"";
        
        if(response && [response isKindOfClass:[NSData class]])
        {
            strResult = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
        }
        else if(response && [response isKindOfClass:[NSDictionary class]])
        {
            NSError *error;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response options:0 error:&error];
            if (! jsonData) {
//                NSLog(@"Got an error: %@", error);
            } else {
                strResult = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            }
        }
        else
        {
            strResult =[[NSString alloc] initWithFormat:@"%@",response];//response;
        }
        
        //
        NSString *urstr =[NSString stringWithFormat:@"%@%@",post_url,[ZShare publicParams]];
        urstr = [urstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSString *  strLocationTime=[ZShare nsdateToString:[NSDate date]];
        NSString *keyword =[searchTerm stringByReplacingOccurrencesOfString:@"+" withString:@" "];
        keyword =[searchTerm stringByReplacingOccurrencesOfString:@"&" withString:@" "];
//        sign=md5(private_key+urlencode(keywords)+uuid+时间戳)
        NSString *sign =[NSString stringWithFormat:@"84Qq8vzB6vM5PsB2%@%@%@",keyword,[ZShare sharedInstance].getUUID,strLocationTime];
       NSString *strMD5 = [ZShare md5:sign];
        NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: strResult, @"data",
                                strMD5, @"sign",//加密后的md5
                                strLocationTime, @"time", nil];
        strResult=nil;
        __weak typeof (self) wSelf = self;
        
        [[SVHTTPClient sharedClient] POST:urstr parameters:params completion:^(id res, NSHTTPURLResponse *urlResponse, NSError *error)
         {
             if(res == nil)
                 return ;
              ++wSelf.process;
              [wSelf updateProgress];
             
             NSDictionary* dcRes = [NSJSONSerialization JSONObjectWithData:res options:kNilOptions error:&error];
             if (dcRes && [dcRes isKindOfClass:[NSDictionary class]])
             {
                 //更新公共参数
                 NSMutableArray *searcharray =[NSMutableArray array];
                 NSArray* relate = [dcRes arrayObjectForKey:@"relate"];
                 if (relate && [relate isKindOfClass:[NSArray class]])
                 {
                     [searcharray addObjectsFromArray:relate];
                 }
                 NSArray* search = [dcRes arrayObjectForKey:@"search"];
                 if (search && [search isKindOfClass:[NSArray class]])
                 {
                     [searcharray addObjectsFromArray:search];
                 }
                 if (searcharray.count > 0)
                 {
                     [[ZShare sharedInstance] setSearchParamsArray:searcharray];
                     _baseData = searcharray;
                 }
                 else
                 {
                     _baseData = [ZShare sharedInstance].searchParamsArray;
                 }
                 
                 NSDictionary * sugg = [dcRes dictionaryObjectForKey:@"sugg"];
                 if (sugg && [sugg isKindOfClass:[NSDictionary class]])
                 {
                     [[ZShare sharedInstance] setSuggParamsArray:sugg];
                     _recommendURL =sugg;
                 } else {
                     _recommendURL =[ZShare sharedInstance].suggParamsArray;
                 }
                 
                 
                 NSArray* more_search = [dcRes arrayObjectForKey:@"global_search"];
                 if (more_search && [more_search isKindOfClass:[NSArray class]] && more_search.count > 0)
                 {
                     
                      NSString* strEnKeywords = [dcRes stringForKey:@"global_keywords" withDefaultValue:@""];
                      if(strEnKeywords && [strEnKeywords isEqual:_strSearchTermEnglish] == NO)
                      {
                          _strSearchTermEnglish = strEnKeywords;
                         
                          [self searchKey:strEnKeywords urlData:more_search resetProgressData:NO];
                          self.totoalProgress += more_search.count;
     
                      }
                 }
                 
                 
                 
                 
                 
                 //footview
                 
                  if(wSelf.process >= wSelf.totoalProgress)
                  {
     
                      id msg =[dcRes stringForKey:@"end_msg" withDefaultValue:@""];
                      if( msg && [msg isKindOfClass:[NSString class]])
                      {
                          wSelf.tbView.tableFooterView = [self footerView:msg];
                      }
                  }
                 
                 BOOL bNeedReload = NO;
                 
                 NSString* info_url =[dcRes stringForKey:@"info_url" withDefaultValue:@""];
                 NSString* info_sort =[dcRes stringForKey:@"info_sort" withDefaultValue:@""];
                 if (info_url && info_sort.length==0) {
                     info_sort=@"0.5";
                 }
                 
                 
                 NSArray* info =[dcRes arrayObjectForKey:@"info"];
                 if (info && [info isKindOfClass:[NSArray class]]) {
                     NSArray *infoArray =(NSArray*)info;
                     if (infoArray.count>0) {
                         NSMutableDictionary* dcResult = [NSMutableDictionary dictionary];
                         [dcResult addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:
                                                             info_url, @"url",
                                                             @"baidu", @"key",//标题
                                                             info_sort, @"sort", //百度的网址
                                                             @"相关资讯", @"name", //百度的网址
                                                             infoArray, @"data",
                                                             nil]];
                         
                         
                         [wSelf.resultArray addObject:dcResult];
                         bNeedReload = YES;
                     }
                     
                 }
                 
                 NSArray* data = [dcRes arrayObjectForKey:@"data"];
                 if (data && [data isKindOfClass:[NSArray class]])
                 {
                     NSArray *dataa =(NSArray*)data;
                     if (dataa.count>0)
                     {
                         NSString *strKey =[dcRes stringForKey:@"key" withDefaultValue:@""];
                         if([strKey isEqual:@"tb"])
                         {
                             [_dcTaobaoSku removeAllObjects];
                             //是淘宝，需要把淘宝的详情界面里面的SKU拆出来
                             for (int i = 0; i < [dataa count]; i++)
                             {
                                 NSDictionary* dcTaobao = [dataa objectAtIndex:i];
                                 [wSelf getTaobaoDetail:dcTaobao];
                             }
                         }
                         [wSelf.resultArray addObject:dcRes];
                         
                         NSString* strAvgPrice =[dcRes stringForKey:@"avg_price" withDefaultValue:@""];
                         NSString* strName = [dcRes stringForKey:@"name" withDefaultValue:@""];
                         [wSelf.tableProgressBar setComplete:strName price:strAvgPrice];
                         
                         
                         bNeedReload = YES;
                     }
                 }
                 
                 if(bNeedReload)
                 {
                     wSelf.resultArray =[ZShare sortArray:wSelf.resultArray];
                     [wSelf tableReload];
                     
                 }
             }
         }
         ];
    }
   
    
}
- (void) getTaobaoDetail:(NSDictionary* )dcTaobao
{
    
    if(dcTaobao == nil || [dcTaobao isKindOfClass:[NSDictionary class]] == NO)
        return;
    @autoreleasepool
    {
        //todo：应该让haoqingsheng直接输出一个tbid，客户端判断tbid不为空，再进行抓取详情界面信息的操作。
        NSString* strURL = [dcTaobao stringForKey:@"url" withDefaultValue:@""];
        NSRange rangeBegin = [strURL rangeOfString:@"/i"];
        if(rangeBegin.location == NSNotFound)
        {
            return;
        }
        NSRange rangeEnd = [strURL rangeOfString:@".htm"];
        if(rangeEnd.location == NSNotFound)
        {
            return;
        }
        rangeBegin.location += rangeBegin.length;
        rangeBegin.length = rangeEnd.location - rangeBegin.location;
        
        NSString * strID = [strURL substringWithRange:rangeBegin];
        NSString* strAppURL = [NSString stringWithFormat:@"http://hws.m.taobao.com/cache/wdetail/5.0/?id=%@", strID];
        
        [[SVHTTPClient sharedClient] GET:strAppURL parameters:nil completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error)
         {
             //  NSLog(@"%@", response);
             NSDictionary * dcResSkuPage = response;
             
             if(dcResSkuPage && [dcResSkuPage isKindOfClass:[NSDictionary class]])
             {
                 NSDictionary * dcTaobaoData = [dcResSkuPage dictionaryObjectForKey:@"data"];
                 if(dcTaobaoData && [dcTaobaoData isKindOfClass:[NSDictionary class]])
                 {
                     
                     NSDictionary * dcSku = [dcTaobaoData dictionaryObjectForKey:@"skuModel"];
                     
                     if(dcSku && [dcSku isKindOfClass:[NSDictionary class]])
                     {
                         NSArray * arSkuProps = [dcSku arrayObjectForKey:@"skuProps"];
                         if(arSkuProps && [arSkuProps isKindOfClass:[NSArray class]])
                         {
                             
                             NSArray* arSkuNames = [NSArray array];
                             NSArray* arSizeNames = [NSArray array];
                             
                             for( int nn = 0; nn < arSkuProps.count; nn++)
                             {
                                 
                                 NSDictionary * dcSKU = [arSkuProps objectAtIndex:nn];
                                 
                                 NSString *strPropId =[dcSKU stringForKey:@"propId" withDefaultValue:@""];
                                 
                                 if([strPropId isEqual:@"1627207"])//颜色分类，其实还有尺码，但是尺码太多了，显示出来没有意义，因为界面空间不足
                                 {
                                     
                                     arSkuNames = [dcSKU arrayObjectForKey:@"values"];
                                     if(arSkuNames == nil || [arSkuNames isKindOfClass:[NSArray class]] == NO)
                                     {
                                         continue;
                                     }
                                     
                                     [_dcTaobaoSku addEntriesFromDictionary:[NSDictionary dictionaryWithObject:arSkuNames forKey:strID]];
                                     
                                     [_tbView reloadData];
                                     
                                     break;//目前阶段，显示出颜色分类就足够了. 因为界面空间不够
                                     
                                 }
                                 else if([strPropId isEqual:@"20509"])
                                 {
                                     arSizeNames = [dcSKU arrayObjectForKey:@"values"];
                                 }
                                 
                             }
                             if([arSkuNames count] == 0)
                             {
                                 //没有找到颜色分类，这个时候可以显示 尺码
                                 
                                 if(arSizeNames && [arSizeNames isKindOfClass:[NSArray class]])
                                 {
                                     [_dcTaobaoSku addEntriesFromDictionary:[NSDictionary dictionaryWithObject:arSizeNames forKey:strID]];
                                     [_tbView reloadData];
                                 }
                                 
                             }
                             
                             
                             arSkuNames = nil;
                             arSizeNames = nil;
                         }
                         
                     }
                 }
                 
             }
         }];
    }
   
    
}
-(void) moreAction:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    if (btn.tag>[self.resultArray count])
    {
        return;
    }
    
    id obj = [self.resultArray objectAtIndex:btn.tag];
    if (obj && [obj isKindOfClass:[NSDictionary class]])
    {
//        NSString *name =[obj stringForKey:@"url" withDefaultValue:@""];
        NSString *url =[obj stringForKey:@"url" withDefaultValue:@""];
        NSString *key =[obj stringForKey:@"key" withDefaultValue:@""];
        if([key isEqual: @"baidu"])
        {
            WebViewController *shaidanweb =[[WebViewController alloc] init];
            shaidanweb.titlestr= @"search";
            shaidanweb.urlstr=url;
            [self.navigationController pushViewController:shaidanweb animated:YES];
            shaidanweb=nil;
            
            return;
        }
    }
    
    NSString *name =[obj stringForKey:@"name" withDefaultValue:@""];
    if([_strNameExpanded isEqual:name])
    {
        _strNameExpanded = @"";
    }
    else
    {
        _strNameExpanded = name;
    }
 /*
    if(_nShowMoreData == btn.tag)
    {
        
        _nShowMoreData = -1;
    }
    else
    {
        _nShowMoreData = btn.tag;
    }
    //*/
    [_tbView reloadData];
    
    return;
    
}





@end
